package com.test.utils;

import java.math.BigInteger;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

public class ShortIdGenerator {

    private static final String CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static final BigInteger BASE = BigInteger.valueOf(62);

    /**
     * 生成短ID
     * 具体过程：
     * 1. 获取UUID
     * 2. 去掉UUID中的连字符
     * 3. 将UUID按十六进制转成BigInteger
     * 4. 将BigInteger进行Base62编码
     * 
     * @return 生成的短ID
     */
    public static String generateShortId() {
        // 获取UUID并去掉连字符
        String uuid = UUID.randomUUID().toString().replace("-", "");
        
        // 将UUID按十六进制转成BigInteger
        BigInteger number = new BigInteger(uuid, 16);
        
        // 将BigInteger进行Base62编码
        return toBase62(number);
    }
    
    /**
     * 将BigInteger转换为Base62编码的字符串
     * 
     * @param number 要转换的BigInteger
     * @return Base62编码的字符串
     */
    private static String toBase62(BigInteger number) {
        StringBuilder sb = new StringBuilder();
        BigInteger value = number;
        
        while (value.compareTo(BigInteger.ZERO) > 0) {
            BigInteger[] divAndRem = value.divideAndRemainder(BASE);
            sb.append(CHARACTERS.charAt(divAndRem[1].intValue()));
            value = divAndRem[0];
        }
        
        return sb.reverse().toString();
    }
    
    /**
     * 测试方法
     */
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        final Set<String> s = new HashSet<>();
        for (int i = 0; i < 100000; i++) {
            s.add(generateShortId());
        }
        System.out.println(s.size());
        System.out.println(System.currentTimeMillis() - start);
    }
}